import json

from .control import voltage_control as voltage_control
from ..micro_grid import micro_system as micro_system
from ..grid_data import jsondata_utils as jsondata_utils


class operation_entry():
    # Get input data in json format
    def __init__(self):
        self.micro_grid = None

        self.v_control = None

    #
    def on_process_request(self, req):

        # Step 1:  Read in load input in Json
        request = json.loads(req)

        # Only if reset system is enabled or first time

        #if input_data["Input"]["reset_grid"] == 1:
        if self.micro_grid is None:

            # Initialize current micro grid
            self.micro_grid = micro_system.micro_system(request["Microgrid"])

            # Initialize modules
            self.v_control = voltage_control.voltage_control(self.micro_grid, req)

        # Only if economic dispatch is enabled
        if request["Parameters"]["economic_dispatch"] == 1:

            # Read in load data (required), price data (required)
            load = request["load"]

            # Read in price data
            price = request["price"]

            #Read in pv
            pv = request["pv"]["kw"]

        # Do voltage control
        if request["Parameters"]["voltage_control"] == 1:
            # Step 1: Get reading for each device
            for device in self.micro_grid.device_list:
                P = jsondata_utils.getValue(request["Measurement"], device.dev_id, 'P')#
                Q = jsondata_utils.getValue(request["Measurement"], device.dev_id, 'Q')#
                device.P = P
                device.Q = Q

            # Step 2: Get reading from micro-grid for voltage control
            Vl_p = jsondata_utils.getValue(request["Measurement"], 0, 'Vp')#10
            Vl_q = jsondata_utils.getValue(request["Measurement"], 0, 'Vq')#5
            Il_p = jsondata_utils.getValue(request["Measurement"], 0, 'Ip')#2
            Il_q = jsondata_utils.getValue(request["Measurement"], 0, 'Iq')#1

            control_command_str = self.v_control.voltage_control( Vl_p, Vl_q, Il_p, Il_q)

            return control_command_str
